<?php 

/**
 * Ajax_SaveEvent.phtml - Sauvegarde d'un évènement
 *
 * @package
 * @author Alexis Eric
 * @copyright Copyright (c) 2012 - Erra Prod
 * @version $1.0$
 * @access public
 */
foreach ($_POST['SAVE_EVENT'] as $calEvent) {
    $eventClasses = array('presta' => 'Msa_SlotObject', 'slot' => 'Msa_SlotObject', 'web' => 'Msa_SlotObject');
    $eventClass = $eventClasses[$calEvent['event_type']];
    $field = $eventClass::create($calEvent['id']);
    $potentialId = Erra_Core_DatabasePdo::SELECT('SELECT id FROM msa_slotobject WHERE msa_slotobject.object_id ="' . $field->getObjectId() . '"');
    if (Erra_Core_DatabasePdo::rowCount()) {
        $potentialId = $potentialId->fetch();
        $field->setId($potentialId->id);
    }
    $rawData = array('title' => $calEvent['title'],
        'event_type' => $calEvent['event_type'],
        'agenda_id' => $calEvent['agenda_id'],
        'event_id' => $calEvent['id'],
        'slot_day' => $calEvent['slot_day'],
        'slot_start' => $calEvent['slot_start'],
        'slot_end' => $calEvent['slot_end'],
        'slot_color' => $calEvent['color'],
        'status_rdv' => $calEvent['status_rdv'],
        'prestation_id' => $calEvent['prestation_id'],
        'date_commande' => $calEvent['date_commande'],
        'from_internet' => $calEvent['from_internet'],
        'last_sync' => time(),
        'title' => $calEvent['title'],
    );
    for ($i = 0; $i <= 5; $i++) {
        if (isset($calEvent['extra_field_' . $i])) {
            $rawData['extra_field_' . $i] = $calEvent['extra_field_' . $i];
        }
    }
    // STANDARD EVENTS
    //////////////////
    if (isset($calEvent['client_id'])) {
        $rawData['client_id'] = $calEvent['client_id'];
        $rawData['prestation_id'] = $calEvent['prestation_id'];
    }

    // SLOT EVENTS
    //////////////
    if (isset($calEvent['repeat_enabled'])) {
        $rawData['client_id'] = 0;
        $rawData['prestation_id'] = 0;
        $rawData['prestation'] = $calEvent['prestation'];
        $bHasBeenSeparated = false;
        if (is_numeric($calEvent['occurency']) && $calEvent['occurency'] >= 0) {
            $prestation = Erra_Core_DatabasePdo::SELECT('SELECT prestation FROM msa_slotobject WHERE event_id="' . $calEvent['id'] . '"');
            if (Erra_Core_DatabasePdo::rowCount()) {
                // Its an occurency, if prestation differs, explode this object into another single event
                $prestation = $prestation->fetch();
                if ($prestation->prestation != $calEvent['prestation']) {
                    // Create a separated slot
                    $bHasBeenSeparated = true;
                    $rawData['prestation'] = $calEvent['prestation'];
                    $rawData['event_id'] = $rawData['object_id'] = uniqid();
                    $rawData['slot_day'] = strtotime(date("Y-m-d", strtotime($calEvent['start'])));
                    // Set default event properties
                    $rawData['repeat_enabled'] = '';
                    $rawData['occurency'] = 'original';
                    $rawData['deleted_occurencies'] = '';
                    $rawData['repeat_time'] = '1';
                    $rawData['repeat_period'] = 'jour';
                    $rawData['repeat_occurency'] = 'always';
                    $rawData['repeat_on_specific_days'] = '';
                    // Allow slot to be inserted
                    $field->setObjectId($rawData['object_id']);
                    $field->setId(-1);
                    // Add this slot to deleted occurencies
                    Erra_Core_DatabasePdo::EXECUTE('UPDATE msa_slotobject SET deleted_occurencies = CONCAT("' . $calEvent['occurency'].';' . '", deleted_occurencies) WHERE object_id="' . $calEvent['id'] . '"');
                }
            }
        }
        if (!$bHasBeenSeparated) {
            $rawData['repeat_enabled'] = $calEvent['repeat_enabled'];
            $rawData['repeat_occurency'] = $calEvent['repeat_occurency'];
            $rawData['repeat_occurency_date'] = $calEvent['repeat_occurency_date'];
            $rawData['repeat_period'] = $calEvent['repeat_period'];
            $rawData['repeat_time'] = $calEvent['repeat_time'];
            $rawData['occurency'] = $calEvent['occurency'];
            $rawData['deleted_occurencies'] = $calEvent['deleted_occurencies'];
            if (isset($calEvent['repeat_on_specific_days'])) {
                $rawData['repeat_on_specific_days'] = $calEvent['repeat_on_specific_days'];
            }
        }
        $rawData['content'] = $calEvent['content'];
    }
    // Merge array items
    $field->setRawData($rawData);

    // Standard save event function
    if ($field->event_type->value == 'presta') {
        $rdv = Erra_Core_DatabasePdo::SELECT('SELECT msa_agendaobject.email AS presta_email, msa_agendaobject.telephone_portable AS presta_portable, slot_day, slot_start, nom, prenom, msa_clientobject.email AS user_mail, msa_clientobject.telephone_portable AS user_portable FROM msa_slotobject, msa_clientobject, msa_agendaobject WHERE msa_slotobject.object_id ="' . $field->getObjectId() . '" AND msa_clientobject.id=msa_slotobject.client_id AND msa_agendaobject.id=msa_slotobject.agenda_id');
        if (Erra_Core_DatabasePdo::rowCount() && is_object($rdv)) {
            // Editer un rendez vous
            //////////////////////
            $rdv = $rdv->fetch();
            Erra_System_Factory::saveField($field, 'SQL');
            if ($rdv->slot_start != $field->slot_start->value || $rdv->slot_day != $field->slot_day->value) {
                // Get placeholders
                // Only send mail if booking is in the future
                if ($field->slot_start->value > time()) {
                    $nom_complet = $rdv->nom . ' ' . $rdv->prenom;
                    $date_reservation = date('d/m/Y', $rdv->slot_day);
                    $heure_reservation = time_to_str_hour($rdv->slot_start);
                    $nom_etablissement = Config_GeneralConfigObject::get('nom_etablissement');
                    $nouvelle_date_reservation = date('d/m/Y', $rdv->slot_day);
                    $nouvelle_heure_reservation = time_to_str_hour($rdv->slot_start);
                    $placeHolders = array('{nom_complet}' => $nom_complet,
                        '{date_reservation}' => $date_reservation,
                        '{heure_reservation}' => $heure_reservation,
                        '{nom_etablissement}' => $nom_etablissement,
                        '{nouvelle_date_reservation}' => $nouvelle_date_reservation,
                        '{nouvelle_heure_reservation}' => $nouvelle_heure_reservation);

                    $result = Erra_Utils_Tools::sendTemplatedMail($rdv->user_mail, 'Mail/Mail_RdvEditClient.phtml', $placeHolders);
                    if (Config_GeneralConfigObject::get('sms_client_moverdv') == 1) {
                        $result = Erra_Utils_Tools::sendTemplatedSms($rdv->user_portable, 'Sms/Sms_RdvEditClient.phtml', $placeHolders);
                    }
                    if (Config_GeneralConfigObject::get('mail_team_moverdv') == 1) {
                        $result = Erra_Utils_Tools::sendTemplatedMail($rdv->presta_email, 'Mail/Mail_RdvEditPresta.phtml', $placeHolders);
                    }
                    if (Config_GeneralConfigObject::get('sms_team_moverdv') == 1 && Config_GeneralConfigObject::get('sms_team_internetonly') != 1) {
                        $result = Erra_Utils_Tools::sendTemplatedSms($rdv->presta_portable, 'Sms/Sms_RdvEditPresta.phtml', $placeHolders);
                    }
                }
            }
        } else {
            // Créér un rendez-vous
            ///////////////////////
            Erra_System_Factory::saveField($field, 'SQL');

            $rdv = Erra_Core_DatabasePdo::SELECT('SELECT msa_agendaobject.email AS presta_email, prestation_name, internet_name, msa_agendaobject.telephone_portable AS presta_portable, slot_day, slot_start, from_internet, nom, prenom, msa_clientobject.email AS user_mail, msa_clientobject.telephone_portable AS user_portable FROM msa_slotobject, msa_clientobject, msa_agendaobject, msa_prestationobject WHERE msa_slotobject.object_id ="' . $field->getObjectId() . '" AND msa_clientobject.id=msa_slotobject.client_id AND msa_agendaobject.id=msa_slotobject.agenda_id AND msa_prestationobject.id=' . $field->prestation_id->value);
            if (is_object($rdv)) {
                $rdv = $rdv->fetch();
                // Client side
                ///////////////
                if ($rdv->slot_day + $rdv->slot_start > time()) {
                    $prestation_name = strlen($rdv->internet_name) ? $rdv->internet_name : $rdv->prestation_name;
                    $nom_complet = $rdv->nom . ' ' . $rdv->prenom;
                    $date_reservation = date('d/m/Y', $rdv->slot_day);
                    $heure_reservation = time_to_str_hour($rdv->slot_start);
                    $nom_etablissement = Config_GeneralConfigObject::get('nom_etablissement');
                    $nouvelle_date_reservation = date('d/m/Y', $field->slot_day->value);
                    $nouvelle_heure_reservation = time_to_str_hour($field->slot_start->value);
                    $placeHolders = array('{nom_complet}' => $nom_complet,
                        '{date_reservation}' => $date_reservation,
                        '{heure_reservation}' => $heure_reservation,
                        '{nom_etablissement}' => $nom_etablissement,
                        '{nom_prestation}' => $prestation_name);
                    $result = Erra_Utils_Tools::sendTemplatedMail($rdv->user_mail, 'Mail/Mail_RdvConfirmUser.phtml', $placeHolders);
                    if (Config_GeneralConfigObject::get('sms_client_newrdv') == 1) {
                        $result = Erra_Utils_Tools::sendTemplatedSms($rdv->user_portable, 'Sms/Sms_RdvConfirmUser.phtml', $placeHolders);
                    }
                    // Presta side
                    ///////////////
                    $prestaPlaceHolders = array('{nom_client}' => $nom_complet,
                        '{nom_etablissement}' => $nom_etablissement,
                        '{nom_prestation}' => $rdv->prestation_name,
                        '{date_reservation}' => $date_reservation,
                        '{heure_reservation}' => $heure_reservation);
                    if (Config_GeneralConfigObject::get('mail_team_newrdv') == 1) {
                        $result = Erra_Utils_Tools::sendTemplatedMail($rdv->presta_email, 'Mail/Mail_RdvConfirmPresta.phtml', $prestaPlaceHolders);
                    }
                    if (Config_GeneralConfigObject::get('sms_team_newrdv') == 1 && !(Config_GeneralConfigObject::get('sms_team_internetonly') && !$rdv->from_internet)) {
                        $result = Erra_Utils_Tools::sendTemplatedSms($rdv->presta_portable, 'Sms/Sms_RdvConfirmPresta.phtml', $prestaPlaceHolders);
                    }
                }
            }
        }
        // Sync google calendar
        ///////////////////////
        Tools_GCalendarObject::deleteEventFromUniqid($field->getObjectId());
        Tools_GCalendarObject::addEventFromUniqId($field->getObjectId());
    } else {
        // Check if user changed the repeat properties, so we have to reset deleted occurencies
        if ($field->repeat_enabled->value == 'repeat') {
            // Get actual properties and check if they match with the new ones
            $actual_repeat_properties = Erra_Core_DatabasePdo::SELECT('SELECT slot_day, repeat_time, repeat_period, repeat_occurency FROM msa_slotobject WHERE object_id ="' . $field->getObjectId() . '"');
            if (is_object($actual_repeat_properties) && Erra_Core_DatabasePdo::rowCount()) {
                $actual_repeat_properties = $actual_repeat_properties->fetch();
                if ($actual_repeat_properties->repeat_time != $field->repeat_time->value ||
                        $actual_repeat_properties->repeat_period != $field->repeat_period->value ||
                        $actual_repeat_properties->repeat_occurency != $field->repeat_occurency->value) {
                    // Current repeat properties doesn't match with new ones, reset deleted occurencies
                    $field->deleted_occurencies->setValue('');
                }
            }
            if ($field->occurency->value != 'original' && isset($actual_repeat_properties->slot_day) && is_numeric($actual_repeat_properties->slot_day)) {
                $field->slot_day->setValue($actual_repeat_properties->slot_day);
            }
        }
        Erra_System_Factory::saveField($field, 'SQL');
    }
}

    